<?php

/**
 * 微信配置
 */

namespace app\admin\controller;

use think\facade\View;
use think\facade\Lang;
use think\Validate;

/**
 * ============================================================================
 * DSO2O多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class O2oThird extends AdminControl {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'admin/lang/' . config('lang.default_lang') . '/o2o_third.lang.php');
    }

    public function setting() {
        $config_model = model('config');
        if (!request()->isPost()) {
            $list_config = rkcache('config', true);
            View::assign('list_config', $list_config);
            if (config('ds_config.dada_open')) {
                include_once root_path() . 'extend/dada/index.php';
                $res = query_dada('/api/balance/query', json_encode(array('category' => 3)));
                View::assign('res', array(
                    'status' => $res->status,
                    'msg' => $res->msg,
                    'result' => $res->result,
                ));
            }
            $this->setAdminCurItem('setting');
            return View::fetch();
        } else {
            $update_array['dada_open'] = intval(input('post.dada_open'));
            $update_array['dada_app_key'] = input('post.dada_app_key');
            $update_array['dada_app_secret'] = input('post.dada_app_secret');
            $update_array['dada_source_id'] = input('post.dada_source_id');
            $update_array['gaode_key'] = input('post.gaode_key');
            $update_array['gaode_js_key'] = input('post.gaode_js_key');
            if ($update_array['dada_open'] && !($update_array['dada_app_key'] && $update_array['dada_app_secret'] && $update_array['dada_source_id'] && $update_array['gaode_key'] && $update_array['gaode_js_key'])) {
                $this->error(lang('param_error'));
            }
            $result = $config_model->editConfig($update_array);
            if ($result) {
                dkcache('config');
                $this->log(lang('ds_edit') . lang('o2o_third'), 1);
                if ($update_array['dada_open']) {
                    $this->city_refresh();
                } else {
                    $this->success(lang('ds_common_save_succ'), 'O2oThird/setting');
                }
            } else {
                $this->log(lang('ds_edit') . lang('o2o_third'), 0);
            }
        }
    }

    public function city_list() {
        $cache_key = "dada-city-code";
        $result = rcache($cache_key);
        if (empty($result)) {
            include_once root_path() . 'extend/dada/index.php';
            $res = query_dada('/api/cityCode/list', '');
            if ($res->status != 'success') {
                $this->error($res->msg);
            }
            $result = array('city_code' => $res->result);
            wcache($cache_key, $result);
        }
        $city_code = $result['city_code'];
        $area_model = model('area');
        foreach ($city_code as $val) {
            $val['area_list'] = $area_model->getAreaList(array(array('dada_city_code', '=', $val['cityCode'])));
            $city_list[] = $val;
        }
        View::assign('city_list', $city_list);
        $this->setAdminCurItem('city_list');
        return View::fetch();
    }

    public function city_refresh() {
        include_once root_path() . 'extend/dada/index.php';
        $res = query_dada('/api/cityCode/list', '');
        if ($res->status == 'success') {
            $area_model = model('area');
            $area_model->editArea(array('dada_city_code' => ''), '1=1');
            foreach ($res->result as $val) {
                $area_model->editArea(array('dada_city_code' => $val['cityCode']), array(array('area_name', 'like', '%' . $val['cityName'] . '%')));
            }
            $this->success(lang('ds_common_save_succ'), 'O2oThird/setting');
        } else {
            $this->error($res->msg);
        }
    }

    public function city_edit() {
        $cityCode = input('param.cityCode');
        if (empty($cityCode)) {
            $this->error(lang('param_error'));
        }
        $area_model = model('area');
        if (!request()->isPost()) {
            $area = $area_model->getAreaChild();
            if (!empty($area)) {
                $tree = new \mall\Tree();
                $tree->setTree($area, 'area_id', 'area_parent_id', 'area_name');
                $parents = $tree->getOptions(3, 0, NULL);
            } else {
                $parents = array();
            }

            View::assign('parents', $parents);
            $area_list = $area_model->getAreaList(array(array('dada_city_code', '=', $cityCode)));
            View::assign('area_list', $area_list);
            return View::fetch();
        } else {
            $area_id = input('param.area_id/a');
            if (empty($area_id)) {
                $this->error(lang('param_error'));
            }

            $area_model->editArea(array('dada_city_code' => ''), array(array('dada_city_code', '=', $cityCode)));

            $area_model->editArea(array('dada_city_code' => $cityCode), array(array('area_id', 'in', $area_id)));
            dsLayerOpenSuccess(lang('ds_common_op_succ'));
        }
    }

    public function shop_list() {
        include_once root_path() . 'extend/dada/index.php';
        $store_model = model('store');
        $keyword = input('param.keyword');
        $condition = array(
            array('dada_shop_no', '<>', ''),
        );
        if ($keyword) {
            $condition[] = array('store_name|seller_name', 'like', '%' . $keyword . '%');
        }
        $store_list = $store_model->getStoreList($condition, 30, 'store_id desc', 'store_id,store_name,dada_shop_no,seller_name');
        foreach ($store_list as $key => $val) {
            $store_list[$key]['dada_info'] = false;
            $body = array(
                'origin_shop_id' => $val['dada_shop_no'],
            );
            $res = query_dada('/api/shop/detail', json_encode($body));
            if ($res->status == 'success') {
                $store_list[$key]['dada_info'] = $res->result;
            }
        }
        View::assign('store_list', $store_list);
        View::assign('show_page', $store_model->page_info->render());
        $this->setAdminCurItem('shop_list');
        return View::fetch();
    }

    public function shop_edit() {
        include_once root_path() . 'extend/dada/index.php';
        $store_id = intval(input('param.store_id'));
        if (empty($store_id)) {
            $this->error(lang('param_error'));
        }
        $store_model = model('store');
        $store_info = $store_model->getOneStore(array(array('store_id', '=', $store_id)), 'store_id,store_name,store_address,store_longitude,store_latitude,region_id,store_phone,seller_name,dada_shop_no,dada_city_code');
        if (!$store_info) {
            $this->error(lang('param_error'));
        }
        if (!request()->isPost()) {
            $cache_key = "dada-city-code";
            $result = rcache($cache_key);
            if (empty($result)) {
                $res = query_dada('/api/cityCode/list', '');
                if ($res->status != 'success') {
                    $this->error($res->msg);
                }
                $result = array('city_code' => $res->result);
                wcache($cache_key, $result);
            }
            View::assign('city_code',json_encode($result['city_code'],JSON_UNESCAPED_UNICODE));
            //获取地区
            if ($store_info['region_id']) {
                $area_model = model('area');
                $area_info = $area_model->getAreaInfo(array(array('area_id', '=', $store_info['region_id'])));
                if ($area_info) {
                    $area_info['parent'] = $area_model->getAreaInfo(array(array('area_id', '=', $area_info['area_parent_id'])));
                }
            } else {
                $area_info = false;
            }
            //转换坐标
            if ($store_info['store_longitude'] && $store_info['store_latitude']) {
                $res = convert_coordinate($store_info['store_longitude'], $store_info['store_latitude']);
                $res = json_decode($res, true);
                if ($res['status'] == '1') {
                    $temp = explode(',', $res['locations']);
                }
            }
            $dada_info = array(
                'station_name' => $store_info['store_name'],
                'city_name' => ($area_info && $area_info['parent']) ? $area_info['parent']['area_name'] : '',
                'area_name' => $area_info ? $area_info['area_name'] : '',
                'station_address' => $store_info['store_address'],
                'lng' => isset($temp) ? $temp[0] : 0,
                'lat' => isset($temp) ? $temp[1] : 0,
                'phone' => $store_info['store_phone'],
            );
            if ($store_info['dada_shop_no']) {
                $body = array(
                    'origin_shop_id' => $store_info['dada_shop_no'],
                );
                $res = query_dada('/api/shop/detail', json_encode($body));
                if ($res->status == 'success') {
                    $dada_info = array(
                        'origin_shop_id' => $res->result['origin_shop_id'],
                        'station_name' => $res->result['station_name'],
                        'business' => $res->result['business'],
                        'city_name' => $res->result['city_name'],
                        'area_name' => $res->result['area_name'],
                        'station_address' => $res->result['station_address'],
                        'lng' => $res->result['lng'],
                        'lat' => $res->result['lat'],
                        'contact_name' => $res->result['contact_name'],
                        'phone' => $res->result['phone'],
                        'status' => $res->result['status'],
                    );
                }
            }
            View::assign('store_info', $store_info);
            View::assign('dada_info', $dada_info);
            return View::fetch();
        } else {
            if (!input('param.dada_city_code')) {
                $this->error(lang('dada_city_code_not_exist'));
            }
            //如果没有门店编码则新增
            if (!input('param.origin_shop_id')) {
                $body = array(array(
                        'station_name' => input('param.station_name'),
                        'business' => input('param.business'),
                        'city_name' => input('param.city_name'),
                        'area_name' => input('param.area_name'),
                        'station_address' => input('param.station_address'),
                        'lng' => input('param.lng'),
                        'lat' => input('param.lat'),
                        'contact_name' => input('param.contact_name'),
                        'phone' => input('param.phone'),
                ));
                $res = query_dada('/api/shop/add', json_encode($body));
                if ($res->status != 'success') {
                    $this->error($res->msg . lang('dada_station_name_exist'));
                } else {
                    $result = $res->result;
                    if ($result['success'] > 0) {
                        $store_model->editStore(array('dada_shop_no' => $result['successList'][0]['originShopId'], 'dada_city_code' => input('param.dada_city_code'), 'dada_lng_lat' => $body[0]['lng'] . ',' . $body[0]['lat']), array(array('store_id', '=', $store_info['store_id'])));
                    } else {
                        $this->error($result['failedList'][0]['msg']);
                    }
                }
            } else {
                $body = array(
                    'origin_shop_id' => input('param.origin_shop_id'),
                    'station_name' => input('param.station_name'),
                    'business' => input('param.business'),
                    'city_name' => input('param.city_name'),
                    'area_name' => input('param.area_name'),
                    'station_address' => input('param.station_address'),
                    'lng' => input('param.lng'),
                    'lat' => input('param.lat'),
                    'contact_name' => input('param.contact_name'),
                    'phone' => input('param.phone'),
                );
                $res = query_dada('/api/shop/update', json_encode($body));
                if ($res->status != 'success') {
                    $this->error($res->msg);
                } else {
                    $result = $res->result;
                    $store_model->editStore(array('dada_city_code' => input('param.dada_city_code'), 'dada_lng_lat' => $body['lng'] . ',' . $body['lat']), array(array('store_id', '=', $store_info['store_id'])));
                }
            }
            dsLayerOpenSuccess(lang('ds_common_op_succ'));
        }
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'setting',
                'text' => lang('ds_setting'),
                'url' => (string) url('O2oThird/setting')
            ),
        );
        if (config('ds_config.dada_open')) {
            $menu_array[] = array(
                'name' => 'city_list',
                'text' => lang('dada_city_code'),
                'url' => (string) url('O2oThird/city_list')
            );
            $menu_array[] = array(
                'name' => 'shop_list',
                'text' => lang('dada_shop'),
                'url' => (string) url('O2oThird/shop_list')
            );
        }
        return $menu_array;
    }

}
